package utils

import (
	"encoding/json"
	"runtime/debug"
	"signal/lib/trace_log"
	"strings"
)

func Throw(err error) {
	if err != nil {
		panic(err)
	}
}

func ToJsonString(data interface{}) string {
	return string(toJson(data))
}

func ToJsonBytes(data interface{}) []byte {
	return toJson(data)
}

func toJson(data interface{}) []byte {
	if data == nil {
		return nil
	}
	marshal, _ := json.Marshal(data)
	return marshal
}

func ExtractIP(addr string) string {
	parts := strings.Split(addr, ":")
	return parts[0]
}

func Reverse(s []byte) {
	for i := 0; i < len(s)/2; i++ {
		j := len(s) - i - 1
		s[i], s[j] = s[j], s[i]
	}
}

func ExceptionCatch() {
	if err := recover(); err != nil {
		trace_log.ErrorLogger.Error("Exception:", err, " \n", string(debug.Stack()))
	}
}

// splitBytes 将 []byte 分割成指定份数
func SplitBytes(data []byte, splitCount int) [][]byte {
	chunkSize := len(data) / splitCount
	chunks := make([][]byte, splitCount)

	for i := 0; i < splitCount; i++ {
		start := i * chunkSize
		end := start + chunkSize
		if i == splitCount-1 {
			end = len(data)
		}
		chunks[i] = data[start:end]
	}

	return chunks
}

func Getcrc8(data []uint8) uint8 {
	crc := uint8(0) // Initial value
	for _, d := range data {
		crc ^= d
		for i := 0; i < 8; i++ {
			if crc&0x80 != 0 {
				crc = (crc << 1) ^ 0x07
			} else {
				crc <<= 1
			}
		}
	}
	return crc
}
